package com.itzhanshen.auth.processor.impl;

import com.itzhanshen.auth.entity.IntergrationAuthenticationEntity;
import com.itzhanshen.auth.exception.NcOAuth2Exception;
import com.itzhanshen.auth.processor.AuthenticationProcessor;
import com.itzhanshen.sys.feign.SysUserFeign;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NCException;
import com.nineclock.dto.SysUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {
        // 获取数据,手机号及验证码
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");
        if (mobile == null) {
            throw new NCException(ResponseEnum.INVALID_PHONE_NUMBER);
        }
        // 通过手机号获取用户信息
        SysUserDTO sysUserDTO = sysUserFeign.findUserInfo(mobile).getData();
        if (sysUserDTO == null) {
            throw new NCException(ResponseEnum.USER_NOT_FOUND);
        }
        // 构建验证码;
      /*  //
        if ("1234".equals(password)) {
            sysUserDTO.setPassword(bCryptPasswordEncoder.encode(password));
            return sysUserDTO;
        } else {
            throw new NCException(ResponseEnum.CODE_IMAGE_ERROR);
        }*/
        String code = redisTemplate.opsForValue().get(SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile);
        //String code = redisTemplate.boundValueOps(SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile).get();
        if (password.equals(code)) {
            sysUserDTO.setPassword(bCryptPasswordEncoder.encode(password));
            return sysUserDTO;
        } else {
            throw new NcOAuth2Exception(ResponseEnum.CODE_IMAGE_ERROR.getMessage());
        }
    }
    @Override
    public boolean support(IntergrationAuthenticationEntity entity) {
        if (entity != null && "sms".equalsIgnoreCase(entity.getAuthType())) {
            return true;
        }
        return false;
    }
}
